package repository

import (
	"context"
	"time"

	"github.com/devops-smartbot/devops-smartbot/services/api-gateway/internal/models"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

// AnalysisRepository defines interface for ticket analysis data access
type AnalysisRepository interface {
	Create(ctx context.Context, analysis *models.TicketAnalysis) error
	GetByTicketID(ctx context.Context, ticketID string) (*models.TicketAnalysis, error)
	UpdateStatus(ctx context.Context, ticketID string, status models.AnalysisStatus) error
	UpdateResult(ctx context.Context, ticketID string, rootCause, solution, prevention string) error
	UpdateError(ctx context.Context, ticketID string, errorMsg string) error
}

// MongoAnalysisRepository implements AnalysisRepository using MongoDB
type MongoAnalysisRepository struct {
	collection *mongo.Collection
}

// NewMongoAnalysisRepository creates a new MongoDB analysis repository
func NewMongoAnalysisRepository(db *mongo.Database) AnalysisRepository {
	return &MongoAnalysisRepository{
		collection: db.Collection("ticket_analysis"),
	}
}

func (r *MongoAnalysisRepository) Create(ctx context.Context, analysis *models.TicketAnalysis) error {
	analysis.CreatedAt = time.Now()
	analysis.UpdatedAt = time.Now()
	_, err := r.collection.InsertOne(ctx, analysis)
	return err
}

func (r *MongoAnalysisRepository) GetByTicketID(ctx context.Context, ticketID string) (*models.TicketAnalysis, error) {
	var analysis models.TicketAnalysis
	err := r.collection.FindOne(ctx, bson.M{"ticketId": ticketID}).Decode(&analysis)
	if err == mongo.ErrNoDocuments {
		return nil, nil
	}
	return &analysis, err
}

func (r *MongoAnalysisRepository) UpdateStatus(ctx context.Context, ticketID string, status models.AnalysisStatus) error {
	update := bson.M{
		"$set": bson.M{
			"status":    status,
			"updatedAt": time.Now(),
		},
	}
	_, err := r.collection.UpdateOne(ctx, bson.M{"ticketId": ticketID}, update)
	return err
}

func (r *MongoAnalysisRepository) UpdateResult(ctx context.Context, ticketID string, rootCause, solution, prevention string) error {
	now := time.Now()
	update := bson.M{
		"$set": bson.M{
			"status":      models.AnalysisStatusCompleted,
			"rootCause":   rootCause,
			"solution":    solution,
			"prevention":  prevention,
			"updatedAt":   now,
			"completedAt": now,
		},
	}
	_, err := r.collection.UpdateOne(ctx, bson.M{"ticketId": ticketID}, update)
	return err
}

func (r *MongoAnalysisRepository) UpdateError(ctx context.Context, ticketID string, errorMsg string) error {
	update := bson.M{
		"$set": bson.M{
			"status":    models.AnalysisStatusFailed,
			"errorMsg":  errorMsg,
			"updatedAt": time.Now(),
		},
	}
	_, err := r.collection.UpdateOne(ctx, bson.M{"ticketId": ticketID}, update)
	return err
}
